import os 
import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from model import Team


class MainPage(webapp.RequestHandler):

  def get(self):
    user = users.get_current_user()

    if user:
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'
    
    template_values = {
      'url': url,
      'url_linktext': url_linktext,
    }
    self.response.out.write(renderpage('index.html', template_values))


class TeamOverviewPage(webapp.RequestHandler):

  def get(self):
    if users.get_current_user():
      teams = Team.gql('WHERE owner = :1 ORDER BY name', 
	users.get_current_user())
      template_values = {
        'teams': teams,
      }
      self.response.out.write(renderpage('team_overview.html', template_values))
    else:
      self.redirect(users.create_login_url(self.request.uri))

class TeamAddPage(webapp.RequestHandler):

  def get(self):
    if users.get_current_user():
      self.response.out.write(renderpage('team_create.html', {}))
    else:
      self.redirect(users.create_login_url(self.request.uri))

  def post(self):
    logging.debug('Creating a new team')
    if users.get_current_user():
      team = Team()
      team.owner = users.get_current_user()
      team.name = self.request.get('name')
      team.put()
      self.redirect('/team/list')


 
application = webapp.WSGIApplication([('/', MainPage), ('/team/list', TeamOverviewPage),('/team/add', TeamAddPage),], debug=True)

def main():
  run_wsgi_app(application)

def renderpage(t, template_values):
  p = os.path.join(os.path.dirname(__file__), 'templates', t)
  return template.render(p, template_values)

if __name__ == '__main__':
  main()
